<template>
    <div>
        <el-button type="success" @click="checkSuccess()">一键审核通过</el-button>
         <el-button type="primary" @click="isShowDialog('insert')">创建采购计划</el-button>
         <el-input placeholder="请输入供应商名称/物料名称" v-model="keywords" class="input-with-select">
            <el-button slot="append" type="primary" icon="el-icon-search" class="searchBtn" @click="searchBtn"></el-button>
        </el-input>

        <!-- 表格 -->
        <el-table :data="tableData" :highlight-current-row="true" stripe border class="table-index"  style="width: 100%;" :height="tableHeight"
        :header-cell-style="getRowClass" v-loading="loading" @sort-change="sortChange" @selection-change="handleSelectionChange">
             <el-table-column type="selection" width="55" :selectable='selectable'></el-table-column>
            <el-table-column prop="supplierName" label="供应商名称" sortable='custom' min-width="140"></el-table-column>
            <el-table-column prop="makeNo" label="令号" sortable='custom' min-width="80"></el-table-column>
            <el-table-column prop="bomName" label="物料名称" sortable='custom' show-overflow-tooltip min-width="140"></el-table-column>
            <el-table-column prop="needNums" label="需求数量" sortable='custom' min-width="90"></el-table-column>
            <!-- <el-table-column prop="inventoryNums" label="库存数量" sortable='custom' show-overflow-tooltip min-width="90"></el-table-column> -->
            <el-table-column prop="price" label="单价" sortable='custom' min-width="70"></el-table-column>
            <el-table-column prop="total" label="总价" sortable='custom' min-width="70"></el-table-column>
            <el-table-column prop="planArriveDate" label="货物最晚到达时间" sortable='custom' min-width="140" :formatter="timesFormatter"></el-table-column>
            <el-table-column prop="needDate" label="订单下达时间" sortable='custom' min-width="120"  :formatter="timesFormatter"></el-table-column>
            <el-table-column prop="deliveryTime" label="计划交货时间" sortable='custom' min-width="120"  :formatter="timesFormatter"></el-table-column>
            <el-table-column prop="planPaymentTime" label="计划付款时间" sortable='custom' min-width="120"  :formatter="timesFormatter"></el-table-column>
            <el-table-column prop="status" label="订单状态" fixed="right" sortable='custom' min-width="90" align="center">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.status==1">审核通过</el-tag>
                    <el-tag type="warning" v-else>审核中...</el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作"  align="center" width="140">
                <template slot-scope="scope">
                    <el-button @click="isShowDialog('update',scope.row)" type="text" size="mini">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[5,10, 15,20, 25,30,50, 100]" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
       <el-dialog :title="dialog.title" width="450px" center :visible.sync="dialog.isShow" :close-on-click-modal="false">
            <div :style="tableDialogHeightTabPane">
            <el-form class="demo-form-inline" v-model="dialogForm" label-position="right" label-width="120px">
                <el-form-item label="机器型号">
                    <el-select v-model="dialogForm.type" placeholder="请选择机器型号">
                        <el-option :label="item.name" :value="item.code" v-for="item in allMachineType" :key="item.code"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数量">
                    <el-input-number v-model="dialogForm.num" controls-position="right" @change="handleChange" :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="令号"><el-input v-model="dialogForm.makeNo" ></el-input></el-form-item>
                <el-form-item label="需求日期"><el-date-picker v-model="dialogForm.needDate" type="date" placeholder="选择日期"> </el-date-picker></el-form-item>
            </el-form>
                </div>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="createPlan" type="primary">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="dialog1.title" width="800px" center :visible.sync="dialog1.isShow" :close-on-click-modal="false">
            <div :style="tableDialogHeightTabPane">
            <el-form class="demo-form-inline" v-model="dialogForm1" label-position="right" label-width="140px" :inline="true">
                <el-form-item label="供应商名称">
                    <el-autocomplete  class="autocomplete-row" v-model="dialogForm1.supplierName" :fetch-suggestions="querySearchAsync1" placeholder="请输入物料名称" @select="handleSelect1"></el-autocomplete>
                </el-form-item>
                <el-form-item label="物料名称"><el-input v-model="dialogForm1.bomName" disabled></el-input></el-form-item>
                <el-form-item label="令号"><el-input v-model="dialogForm1.makeNo" disabled></el-input></el-form-item>
                <el-form-item label="需求数量"><el-input v-model="dialogForm1.needNums" ></el-input></el-form-item>
                <el-form-item label="库存数量"><el-input v-model="dialogForm1.inventoryNums" ></el-input></el-form-item>
                <el-form-item label="单价"><el-input v-model="dialogForm1.price"></el-input></el-form-item>
                <el-form-item label="总价"><el-input v-model="dialogForm1.total" ></el-input></el-form-item>
                <el-form-item label="货物预计到达日期">
                      <el-date-picker  v-model="dialogForm1.planArriveDate" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="订单下达时间">
                     <el-date-picker  v-model="dialogForm1.needDate" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                 <el-form-item label="计划付款时间">
                     <el-date-picker  v-model="dialogForm1.planPaymentTime" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                 <el-form-item label="审核是否通过">
                    <el-select v-model="dialogForm1.status" placeholder="请选择">
                        <el-option :label="item.label" :value="item.value" v-for="item in isCheckedList" :key="item.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="创建人"><el-input v-model="dialogForm1.createorName" disabled></el-input></el-form-item>
                  <el-form-item label="创建时间"><el-input v-model="dialogForm1.createTime" disabled></el-input></el-form-item>
            </el-form>
                </div>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="submitClick" type="primary">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import api from '@/axios/api.js'
export default {
    data(){
        return {
            tableHeight: document.documentElement.clientHeight - 170,/**表格高度 */
            tableDialogHeightTabPane:{/**dialog style */
                height: (document.documentElement.clientHeight - 300) + 'px',
                overflowY: 'auto'
            },
            userId:sessionStorage.getItem("userId"),
            allMachineType:[],/*所有机器型号列表*/
            allSupplier:[],/**所有供应商列表 */
            tableData:[],
            loading:false,/**加载参数 */
             keywords:'',/**关键字 */
             sort:{/**排序 */
                sortBy:'',
                desc:null,
            },
            pagination:{/**分页 */
                pageSize:10,
                currentPage:1,
                total:0
            },
            dialog:{/**弹框配置 */
                title:'',
                isShow:false,
            },
            dialog1:{/**弹框1配置 */
                title:'',
                isShow:false,
            },
            dialogForm:{},
            dialogForm1:{},
            isCheckedList:[/**订单审核参数 */
                {
                    label:'通过',
                    value:'1'
                },
                {
                    label:'不通过',
                    value:'0'
                }],
            selectList:[],

        }
    },
    created () {
        let self = this;
        self.getTableList();
         api.allSupplierList().then(res=>{
             /**获取所有供应商列表 */
             if(res.content.length>0){
                 res.content.forEach(el => {
                     el.value =el.name;
                     self.allSupplier.push({
                         name:el.name,
                         value:el.name,
                         id:el.id
                     });
                 });
             }
        })
        api.machineTypeCode(4).then(res=>{
            self.allMachineType = res.content;
        })
    },
    methods:{
        getTableList(){
            let self = this;
            self.loading=true;
            let data={
                currentPage:self.pagination.currentPage,
                pageSize:self.pagination.pageSize,
                sortBy:self.sort.sortBy,
                desc:self.sort.desc,
                key:self.keywords
            }
            api.purchasePlanList(data).then(res=>{
                self.loading=false;
                self.tableData=res.content.items;
                self.pagination.total = res.content.total;
            },error=>{
                 self.loading=false;
            })
        },
        timesFormatter(row, column, cellValue, index){
            return cellValue?this.timestampToTime1(cellValue,'yy-mm-dd'):'';
        },
        isShowDialog(type,row){
            let self = this;
            if(type==='insert'){
                self.dialog.title = '新增';
                self.dialog.isShow=true;
                self.dialogForm={
                    type:'',
                    num:1,
                    needDate:'',
                    makeNo:'',
                }
            }else{
                self.dialog1.title ='编辑';
                self.dialog1.isShow=true;
                self.dialogForm1={
                    bid: row.bid,
                    bomName: row.bomName,
                    id:row.id,
                    inventoryNums:row.inventoryNums,
                    miniPurchase:row.miniPurchase,
                    needDate:row.needDate?this.timestampToTime1(row.needDate,'yy-mm-dd'):'',
                    needNums:row.needNums,
                    planArriveDate:row.planArriveDate?this.timestampToTime1(row.planArriveDate,'yy-mm-dd'):'',
                    planPaymentTime:row.planPaymentTime?this.timestampToTime1(row.planPaymentTime,'yy-mm-dd'):'',
                    price:row.price,
                    sid:row.sid,
                    makeNo:row.makeNo,
                    status:String(row.status),
                    supplierName:row.supplierName,
                    total:row.total,
                    paymentMethod:row.paymentMethod,
                    createorName:row.createorName,
                    createTime:row.createTime
                }

            }
        },
        handleSizeChange(size){
            this.pagination.currentPage=1;
            this.pagination.pageSize=size;
            this.getTableList();
        },
        handleCurrentChange(current){
            this.pagination.currentPage=current;
            this.getTableList();
        },
        searchBtn(){
            this.pagination.currentPage=1;
            this.getTableList();
        },
        sortChange(sort){/**点击排序 */
            if(sort.order===null){
                this.sort.sortBy='';
                this.sort.desc=null;
            }else{
                this.sort.sortBy=sort.prop;
                this.sort.desc = sort.order==='ascending'?false:true;
            }
            this.pagination.currentPage=1;
            this.getTableList();
        },
        createPlan(){
           let self = this;
           let data={
               type:self.dialogForm.type,
               num:self.dialogForm.num,
               needDate:self.timestampToTime(self.dialogForm.needDate).split(' ')[0],
               makeNo:self.dialogForm.makeNo
           }
           api.createPurchasePlan(data).then(res=>{
               self.dialog.isShow=false;
               self.getTableList();
               self.$message.success(`采购计划创建成功`)
           },error=>{
               self.$message.error(`采购计划创建失败`)
           })
        },
        handleChange(){},
        checkSuccess(){
           let self = this;
            self.$confirm('是否审核通过?', '提示', {
                confirmButtonClass: 'el-button--warning'
                }).then(() => {
                    let postData=[];
                    self.selectList.forEach(el=>{
                        postData.push({
                            bid: el.bid,
                            bomName: el.bomName,
                            id:el.id,
                            createor:self.userId,
                            inventoryNums:el.inventoryNums,
                            miniPurchase:el.miniPurchase,
                            needDate:el.needDate?self.timestampToTime1(el.needDate,'yy-mm-dd hh:mm:ss'):'',
                            needNums:el.needNums,
                            planArriveDate:el.planArriveDate?self.timestampToTime1(el.planArriveDate,'yy-mm-dd hh:mm:ss'):'',
                            planPaymentTime:el.planPaymentTime?this.timestampToTime1(el.planPaymentTime,'yy-mm-dd hh:mm:ss'):'',
                            paymentMethod:el.paymentMethod,
                            price:el.price,
                            sid:el.sid,
                            status:1,
                            makeNo:el.makeNo,
                            supplierName:el.supplierName,
                            total:el.total
                        })
                    })
                    api.updatePurchasePlan(postData).then(res=>{
                        self.getTableList();
                        self.$message.success('审核通过！');
                    },error=>{
                        self.$message.error('审核失败！');
                    })
                }).catch(() => {});
        },
        submitClick(){
           let self = this;
            self.dialogForm1.needDate= self.dialogForm1.needDate?this.timestampToTime1(self.dialogForm1.needDate,'yy-mm-dd hh:mm:ss'):'';
            self.dialogForm1.planArriveDate= self.dialogForm1.planArriveDate?this.timestampToTime1(self.dialogForm1.planArriveDate,'yy-mm-dd hh:mm:ss'):'';
            self.dialogForm1.planPaymentTime=self.dialogForm1.planPaymentTime?this.timestampToTime1(self.dialogForm1.planPaymentTime,'yy-mm-dd hh:mm:ss'):'';
            self.dialogForm1.createor=self.userId;
            let data=[];
            data.push(self.dialogForm1);
             api.updatePurchasePlan(data).then(res=>{
                self.dialog1.isShow = false;
                self.getTableList();
                self.$message.success('采购计划编辑成功！')
            },error=>{
                 self.$message.error('采购计划编辑失败！')
            })
        },
        querySearchAsync1(queryString, callback){
            let results = queryString ?  this.allSupplier.filter(this.createStateFilter(queryString)) : this.allSupplier;
            callback(results);
        },
        handleSelect1(item){
            this.dialogForm1.supplierName=item.name;
            this.dialogForm1.sid=item.id;
        },
        createStateFilter(queryString) {
            return (state) => {
                return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) !==-1);
            };
        },
        handleSelectionChange(val){
            let self = this;
            self.selectList=val;
        },
        selectable(row,index){
            if(row.status==1){
                return false;
            }else{
                return true;
            }
        }
    }
}
</script>
<style scoped>
.autocomplete-row{
    width:450px;
}
.input-with-select{
    width:240px;
}
.searchBtn{
    background: #409eff !important;
    color:#fff !important;
}
</style>
